package com.example.app.controller;

import com.example.app.entity.Message;
import com.example.app.service.MessageService;
import jakarta.annotation.Resource;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class ChatController {
    @Resource
    private SimpMessagingTemplate simpMessagingTemplate;
    @Resource
    private MessageService messageService;

    @MessageMapping("/chat.send")
    public Message handleMessage(Message msg) {
        // save to DB and return
        Message saved = messageService.save(msg);
        simpMessagingTemplate.convertAndSendToUser(
                msg.getToUserId().toString(),   // 接收者的用户ID（字符串）
                "/queue/messages",              // 目标目的地
                saved                           // 发送的消息
        );
        return saved;
    }
}
